import pymysql

'''
mysql 增删查改数据库
b站地址：
https://www.bilibili.com/video/BV1R7411F7JV?p=331&vd_source=76c65c41f1540b9ba0fe6dd3c88615d2
'''
conn = pymysql.connect(host='192.168.235.128', database='my_db', user='root', passwd='123456', charset='utf8')


def insert():
    try:
        with conn.cursor() as cursor:
            res = cursor.execute(
                'insert into  py_test value(%s,%s,%s)', ('3', 'name1', 12,)
            )
            if res == 1:
                print('添加成功！')
            conn.commit()
    except pymysql.Error as error:
        conn.rollback()
        print(error)
    finally:
        conn.close()


def delete():
    no = input('请输入删除编号：')
    try:
        with conn.cursor() as cursor:
            res = cursor.execute(
                'delete from py_test where id=%s', (no,)
            )
            if res == 1:
                print('删除成功！')
            conn.commit()
    except pymysql.Error as error:
        conn.rollback()
        print(error)
    finally:
        conn.close()


def select():
    with conn.cursor() as cursor:
        cursor.execute('select id,name,age from py_test')
        for row in cursor.fetchall():
            print(row[0])
            print(row[1])
            print(row[2])
            print('*' * 20)
    pass


if __name__ == '__main__':
    # insert()
    select()
    # delete()
